package com.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
* 字段校验非空
* */
public class FieldValidateNotNull {
    /*
     * 检验必填属性是否为空!
     * */
    public static <T> String checkRequireParam(T obj, List<String> param) {
        if (null == obj || param.size() == 0) {
            throw new RuntimeException("校验必填属性出错,需要检验的对象和属性不能为空!");
        }
        //获取所有字段
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        //k:属性名  v:属性值
        Map<String, Field> collect = Arrays.stream(declaredFields).collect(Collectors.toMap(Field::getName, (v) -> v));
        StringBuilder errorMsg = new StringBuilder("");
        if (CollUtil.isNotEmpty(collect)) {
            for (String s : param) {
                Field field = collect.get(s);
                if (null != field) {
                    try {
                        field.setAccessible(true);
                        //属性值为空则拼接错误信息
                        Object o = field.get(obj);
                        if (ObjectUtil.isEmpty(o)) {
                            //后续可将属性英文名转为中文命抛出异常
//                            String name = field.getName();
//                            String propDesc = UserPropertiesDesc.getPropDesc(name);
                            errorMsg.append(s).append(",");
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                } else {
                    throw new RuntimeException("属性: " + s + "不存在");
                }
            }
        }
        if (StrUtil.isNotEmpty(errorMsg)){
            throw new RuntimeException("属性: " + errorMsg + "不能为空!");
        }
        return null;
    }

}
